package zhouyang;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

class MyNumber{
     AtomicInteger atomicInteger = new AtomicInteger();
    public void addPlusPlus(){
        atomicInteger.incrementAndGet();
    }
}
public class AtomicIntegerDemo {
    public static final int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i <SIZE; i++) {
            new Thread(()->{
                try {
                    for (int j = 0; j <1000; j++) {
                    myNumber.addPlusPlus();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
//        try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
//       不加这个sleep得不到50000，因为main线程太快了，上面的计算还没完成就来取了,也可以用countDownLatch更精确的等待
        System.out.println(Thread.currentThread().getName()+"\t"+"result:"+myNumber.atomicInteger.get());
    }
}
